package cn.bdqn.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Redis数据库工具
 *
 * @Author XiaoMo
 * @Date 2022/3/17 10:47
 * @Version 1.0
 */
@Component
public class RedisUtil {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource(name = "stringRedisTemplate")
    private ValueOperations<String, String> valueOperations;

    /**
     * 永久存储数据
     * @param key
     * @param value
     */
    public void putValue(String key,String value){
        valueOperations.set(key, value);
    }

    /**
     * 存储数据，含过期时间（秒）
     * @param key
     * @param value
     * @param timeout
     */
    public void putValueTimeout(String key,String value,long timeout){
        valueOperations.set(key, value, timeout, TimeUnit.SECONDS);
    }

    /**
     * 重置过期时间
     * @param key
     * @param timeout
     */
    public void resetExpire(String key,long timeout){
        stringRedisTemplate.expire(key,timeout,TimeUnit.SECONDS);
    }

    /**
     * 读取redis数据
     * @param key
     * @return
     */
    public String get(String key){
        return valueOperations.get(key);
    }

    /**
     * 批量存储
     * @param map
     */
    public void multiPut(Map<String,String> map){
        valueOperations.multiSet(map);
    }

    /**
     * 存储map
     * @param key
     * @param map
     */
    public void  saveMap(String key,Map<String,String> map){
        stringRedisTemplate.opsForHash().putAll(key,map);
    }

    /**
     * 读取map数据
     * @param key
     * @return
     */
    public  Map<Object,Object> getMap(String key){
        return stringRedisTemplate.opsForHash().entries(key);
    }
}
